package com.tronsis.library.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tronsis.library.R;
import com.tronsis.library.widget.LoadingProgressDialog;


/**
 * @author Ross@tronsis.com
 */

public abstract class LazyLoadFragment extends Fragment {
    /**
     * 视图是否已经初初始化
     */
    protected       boolean isInit = false;
    protected       boolean isLoad = false;
    protected final String TAG    = "LazyLoadFragment";
    private View view;
    protected Context mContext;

    private LoadingProgressDialog mLoadingProgressDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = onCreateView();
        isInit = true;
        mContext = getContext();
        onCreateData();
        /**初始化的时候去加载数据**/
        isCanLoadData();
        return view;
    }

    /**
     * 视图是否已经对用户可见，系统的方法
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isInit) {
            return;
        }

        if (getUserVisibleHint()) {
            initData();
            isLoad = true;
        }
    }

    /**
     * 视图销毁的时候讲Fragment是否初始化的状态变为false
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;

    }


    /**
     * 设置Fragment要显示的布局
     * @return 布局的layoutId
     */
    protected abstract View onCreateView();

    /**
     * 初始化时调用
     * @return
     */
    protected abstract void onCreateData();

    /**
     * 当视图初始化并且对用户可见的时候去真正的加载数据
     */
    protected abstract void initData();


    protected void showLoadingDialog() {
        showLoadingDialog("");
    }


    protected void showLoadingDialog(String str) {
        if (mLoadingProgressDialog == null) {
            mLoadingProgressDialog = new LoadingProgressDialog(getContext(), R.style.CustomProgressDialog);
            mLoadingProgressDialog.show(str);
        } else {
            mLoadingProgressDialog.show(str);
        }

    }

    protected void dismissLoadingDialog() {
        if (mLoadingProgressDialog != null) {
            mLoadingProgressDialog.dismiss();
        }
    }



}
